#include "gamestate.h"

#include <QRandomGenerator>

GameState::GameState(QObject *parent)
    : QObject{parent}
{
    connect(this, &GameState::diftyChanged, this, &GameState::onDiftyChanged);
}

void GameState::newLevel() {

    static const int count_cards[] = {4, 6, 8, 10, 12, 14, 16, 18, 20};
    static const int columns[] = {4, 6, 4, 5, 4, 7, 4, 6, 5};

    int idx;

    // EASY
    if (_difty == 0) {
        idx = QRandomGenerator::global()->bounded(0, 3);
    }
    // NORMAL
    else if (_difty == 1) {
        idx = QRandomGenerator::global()->bounded(3, 6);
    }
    // HARD
    else {
        idx = QRandomGenerator::global()->bounded(6, 9);
    }

    // FILL _CARDS
    _column = columns[idx];
    emit columnChanged();

    _cards.resize(count_cards[idx]);

    QList<int> available_cards;
    for (int i = 1; i < 22; ++i) { available_cards.append(i); }  // card1.png - card21.png

    QList<int> available_pos;
    for (int i = 0; i < count_cards[idx]; ++i) { available_pos.append(i); }

    while (available_pos.length()) {
        // ONE CARD
        int card = available_cards[QRandomGenerator::global()->bounded(0, available_cards.length())];
        available_cards.removeOne(card);

        // TWO POSITIONS
        int pos1 = available_pos[QRandomGenerator::global()->bounded(0, available_pos.length())];
        available_pos.removeOne(pos1);
        int pos2 = available_pos[QRandomGenerator::global()->bounded(0, available_pos.length())];
        available_pos.removeOne(pos2);

        _cards[pos1] = _cards[pos2] = card;
    }
    emit cardsChanged();
}

void GameState::onDiftyChanged() {
    qDebug() << "difty: " << _difty;
    newLevel();
}
